<template>
	<ComIndex ref="commonIndexRef" :showFilter="false" :toggleView="false" :isInitList="false">
		<template #search>
			<Search :showSearch="false" :breadCrumb="{ name: bizInfo?.name, breadList: [bizInfo?.menuType === 0 ? 'dataModel' : 'fieldModel', 'settingField'] }">
				<template #right>
					<div v-if="tabValue == '0'">
						<a-button type="primary" @click="handleDetail('')"> <icon-plus />添加字段</a-button>
						<a-button type="primary" status="danger" :disabled="!selectedKeys.length" @click="handleDel"> <icon-minus />删除</a-button>
					</div>
					<div v-if="tabValue == '1'">
						<a-button type="primary" @click="handleRole('')"> <icon-plus />添加权限</a-button>
						<a-button type="primary" status="danger" :disabled="!selectedKeys.length" @click="handleDel"> <icon-minus />删除</a-button>
					</div>
				</template>
			</Search>
		</template>
		<div class="base-padding">
			<ComTips :showTips="tabValue == '0'" :title="bizInfo?.name" tips="自定义客户视图中可用的字段及在客户列表（卡片）视图和客户详情信息视图的显示顺序">
				<ComTabs style="margin-bottom: 10px" v-model="tabValue" :options="fieldTabs" />
			</ComTips>
			<ComTabs v-if="tabValue == '0'" v-model="groupValue" :card="false" style="margin-bottom: 10px" @change="getList" :options="groupList" :prop="{ label: 'name', value: 'id', icon: 'ico' }">
				<template #menuList="{ item }">
					<div class="menu-box">
						<div><a-button type="primary" @click="addGroupRef.edit(item)">编辑</a-button></div>
						<div style="margin-top: 8px">
							<a-popconfirm content="确认删除吗?" @ok="delGroup(item?.id)">
								<a-button>删除</a-button>
							</a-popconfirm>
						</div>
					</div>
				</template>
				<a-button type="primary" class="mr-10" style="border-radius: 6px">
					<template #icon>
						<a-dropdown>
							<div><icon-arrow-right /></div>
							<template #content>
								<a-doption @click="handleMove(item)" v-for="item in groupList" :key="item.id" :disabled="item.id === groupValue || !selectedKeys.length">{{ item.name }}</a-doption>
							</template>
						</a-dropdown>
					</template>
				</a-button>
				<a-input :style="{ width: '300px' }" placeholder="筛选字段" allow-clear v-model="keywords" @keyup.enter="getList">
					<template #prefix>
						<icon-search />
					</template>
				</a-input>
				<template #next>
					<addGroup ref="addGroupRef" :bizId="bizId" @update="getGroupList" />
				</template>
			</ComTabs>
			<ComTable
				:loading="loading"
				row-key="id"
				:editConfig="{ disabled: { field: 'dataType', value: 0 } }"
				:row-selection="rowSelection"
				v-model:selectedKeys="selectedKeys"
				@change="handleChange"
				:draggable="{}"
				@update="setModalRef?.updateFn"
				:pagination="false"
				:columns="columns"
				:data="fieldList"
			>
				<template #name="{ record }">
					<ComLink :text="record.name" :icon="record.ico" @click="handleDetail(record?.id)" :disabled="record.dataType === 0" />
				</template>
				<template #fieldTypeEdit="{ record, setToggle }">
					<a-select
						:bordered="false"
						style="width: 100%"
						@popup-visible-change="setToggle"
						@change="(data) => handleUpdate(data, record)"
						allow-clear
						allow-search
						v-model="record.fieldType"
						:options="showFieldList"
						placeholder="选择数据"
					/>
					<a-link v-if="showSelect(record.fieldType)" style="flex-shrink: 0; margin-left: 8px; font-size: 12px" :hoverable="false" @click="handleSet(setToggle, record)">选项维护</a-link>
				</template>
			</ComTable>
		</div>
		<setModal ref="setModalRef" :bizId="bizId" @update="getList" @cancel="tableToggleFn?.()" />
	</ComIndex>
</template>
<script lang="ts" setup>
import { selectCofnig, sortChange, fieldGroup, deleteFieldGroup, deleteField, configChangeGroup, queryBiz } from "@/api/customerManage/setting";

import ComIndex from "@/components/ComIndex/Index.vue";
import { yesOrNo, fieldDataType, fieldTabs } from "@/utils/filter";
import setModal from "./components/setModal.vue";
import { useMessage } from "@/hooks/useMessage";
import ComTable from "@/components/ComTable/ComTable.vue";
import ComLink from "@/components/ComLink.vue";
import ComTips from "@/components/ComTips.vue";
import addGroup from "./components/addGroup.vue";
import { useShowFieldList } from "@/utils/field";
import { useRouter, useRoute } from "vue-router";

const showFieldList = useShowFieldList();
const selectedKeys = ref([]);
const groupValue: any = ref("");
const router = useRouter();
const addGroupRef = ref({});
const rowSelection = reactive({
	type: "checkbox",
	showCheckedAll: true,
	onlyCurrent: false
});
const route = useRoute();
const message = useMessage();
const commonIndexRef = ref(null);
const setModalRef: any = ref({});
const tabValue = ref("");
const columns = [
	{
		title: "名称",
		slotName: "name",
		width: 270,
		type: "input"
	},
	{
		title: "字段类型",
		slotName: "dataType",
		dict: fieldDataType,
		width: 120
	},

	{
		title: "数据类型",
		slotName: "fieldType",
		dict: showFieldList,
		width: 120
		// edit: true
	},
	{
		title: "是否必填",
		slotName: "isRequired",
		dict: yesOrNo,
		width: 120,
		type: "select",
		options: yesOrNo,
		edit: true
	},
	{
		title: "排序",
		slotName: "sort",
		width: 90,
		sort: true
	}
];

const bizInfo = ref({});
const getDetail = async () => {
	const data = await queryBiz({
		id: bizId.value
	});
	bizInfo.value = data;
};
// 移动字段到别的分组
const handleMove = async (item) => {
	await configChangeGroup({
		configIds: selectedKeys.value,
		groupId: item.id
	});
	groupValue.value = item.id;
	getList();
};
const handleUpdate = (data, row) => {
	if (data === "") return;
	setModalRef.value?.updateFn(row);
};

const delGroup = async (id) => {
	await deleteFieldGroup({ id });
	getGroupList();
};
const tableToggleFn = ref(null);
const handleSet = (fn, row) => {
	fn(true);
	tableToggleFn.value = fn;
	setModalRef.value.setSelectData(row);
};
const showSelect = (data) => {
	return [2, 7, 8].includes(data);
};
const handleChange = async (_data) => {
	fieldList.value = _data;
	const arr = _data.map((item, index) => {
		return {
			key: item.id,
			value: index + 1
		};
	});
	await sortChange(arr);
	message.success("排序成功");
	getList();
};
const fieldList = ref([]);
const bizId: any = ref("");
const loading = ref(false);
const keywords = ref("");
const getList = async () => {
	try {
		selectedKeys.value = [];
		loading.value = true;
		if (tableToggleFn.value) {
			tableToggleFn.value();
		}
		const data = await selectCofnig({ bizId: bizId.value, groupId: groupValue.value, keywords: keywords.value });
		fieldList.value = data;
		updateQuery();
	} catch (error) {
	} finally {
		loading.value = false;
	}
};

const updateQuery = () => {
	// 获取当前的 query 参数
	const currentQuery = { ...route.query };
	// 修改或添加新的 query 参数
	currentQuery.groupValue = groupValue.value;
	// 使用 router.push 更新路由
	router.push({
		query: currentQuery
	});
};

const groupList: any = ref([]);
const getGroupList = async () => {
	const data = await fieldGroup({ bizId: bizId.value });
	groupList.value = [{ name: "未分组", id: "" }, ...data];
};
const handleDetail = (id?) => {
	router.push({
		path: "/settingFieldDetail",
		query: {
			bizId: bizId.value,
			groupId: groupValue.value,
			configId: id
		}
	});
};
const handleRole = (id?) => {
	router.push({
		path: "/settingRoleDetail",
		query: {
			bizId: bizId.value
		}
	});
};

const handleDel = async () => {
	await deleteField({ ids: selectedKeys.value.join(",") });
	getList();
};
watch(
	() => route.query,
	async (data, oldData) => {
		if (data?.id) {
			bizId.value = data.id;
			getDetail();
			if (data.id !== oldData?.id) {
				await getGroupList();
			}
			groupValue.value = data.groupValue ? Number(data.groupValue) : "";
		}
	},
	{ immediate: true }
);
</script>

<style scoped lang="scss">
.menu-box {
	background-color: #fff;
	padding: 16px;
	border-radius: 8px;
	box-shadow: rgba(67, 71, 85, 0.27) 0px 0px 0.25em, rgba(90, 125, 188, 0.05) 0px 0.25em 1em;
}
</style>
